package mysql

import (
	"errors"

	"gorm.io/gorm"

	"mxshop_srvs/userop_srv/model"
)

func (g *Gorm) GetUserFavorites(userID int32) ([]model.UserFav, error) {
	userFavorites := make([]model.UserFav, 0, 8)
	err := g.db.Where(&model.UserFav{
		UserID: userID,
	}).Find(&userFavorites).Error
	return userFavorites, err
}

func (g *Gorm) GetUserFavorite(userID, goodsID int32) (model.UserFav, error) {
	var userFavorite model.UserFav
	err := g.db.Where(&model.UserFav{
		UserID:  userID,
		GoodsID: goodsID,
	}, "UserID", "GoodsID").Take(&userFavorite).Error
	return userFavorite, err
}

func (g *Gorm) GetSoftDelFavorite(userID, goodsID int32) (model.UserFav, error) {
	var userFavorite model.UserFav
	err := g.db.Unscoped().Where(&model.UserFav{
		UserID:  userID,
		GoodsID: goodsID,
	}, "UserID", "GoodsID").Take(&userFavorite).Error
	return userFavorite, err
}

func (g *Gorm) CreateUserFavorites(userID, goodsID int32) (uint, error) {
	// 1.查一下是否已经存在被软删除的收藏
	favorite, err := g.GetSoftDelFavorite(userID, goodsID)
	if err != nil {
		if !errors.Is(err, gorm.ErrRecordNotFound) {
			return 0, err
		}
	}

	// 1.1 如果有则清空DeleteAt
	if favorite.ID != 0 {
		result := g.db.Unscoped().Model(&favorite).Select("DeletedAt").Updates(model.UserFav{
			Model: gorm.Model{DeletedAt: gorm.DeletedAt{}},
		})
		if result.RowsAffected == 0 {
			return 0, err
		}

		return favorite.ID, result.Error
	}

	// 1.2 如果无则插入一条新纪录
	favorite.UserID = userID
	favorite.GoodsID = goodsID
	err = g.db.Create(&favorite).Error

	return favorite.ID, err
}

func (g *Gorm) DeleteUserFavorite(userID, goodsID int32) (int64, error) {
	result := g.db.Where(&model.UserFav{
		UserID:  userID,
		GoodsID: goodsID,
	}, "UserID", "GoodsID").Delete(&model.UserFav{})

	return result.RowsAffected, result.Error
}
